$(function(){
    //初始化总价, 总选择数, 总条数;
    //doPrice();
    //全选/选择框的鼠标移上变个颜色
    $('.check').mouseover(function(){
        if($(this).attr('class')!='check ischecked') {
            $(this).css('color', '#ff6a00');
        }
    })
    $('.check').mouseleave(function(){
        $(this).css('color','#0a0a0a');
    })

    //普通勾选
    //事件委托机制
    // .cart_list_td操作的是子类
    $('#cartList').on('click', '.cart_list_td .check', function (){
        var cla=$(this).attr('class');
        var checked;
        if(cla!='check ischecked'){
            $(this).attr('class','check ischecked');
            checked = 1;
        }else{
            $(this).attr('class','check');
            checked = 0;
        }
        var id = $(this).parents('.cart_list_td').attr('id');
        $.post(
            '/cart/update',
            {'id': id, 'checked': checked},
            function (result) {
                if (result.code == 0) {
                    mylayer.okMsg(result.msg);
                    doCheckAll();
                    doPrice();
                }
            },
            'json'
        );
    });


    //全选框勾选
    $('#check-all').click(function () {
        var cla=$(this).attr('class');
        var checked;

        if(cla!='check ischecked'){
            $('.check').attr('class','check ischecked');
            checked = 1;
        }else{
            $('.check').attr('class','check');
            checked = 0;
        }
        console.log(checked);
        $.post(
            '/cart/updateByUserId',
            {'checked':checked},
            function (result) {
                console.log(result);
                if (result.code == 0){
                    doPrice();
                }
            },
            'json'
        );
    })

    //检查是否全选
    function doCheckAll(){
        var isCheckAll = false;
        var allitem=$('.cart_list_td input[class*="check"]').length;
        var checkeditem=$('.cart_list_td input[class$="ischecked"]').length;
        if(allitem!=checkeditem){
            $('#check-all').attr('class','check');

            console.log('没有全选');
        }else{
            $('#check-all').attr('class','check ischecked');

            console.log('全选');
        }

    }





    //使用委托事件控制加减按钮
    $('#cartList').on('click','.minus',function () {
        var nowvalue=$(this).siblings('input').val();
        nowvalue=parseInt(nowvalue);
        var currentvalue=0;
        nowvalue<=1?currentvalue=1:currentvalue=nowvalue-1;
        $(this).siblings('input').val(currentvalue);
        //用于ajax内的this
        var that = this;
        var id=$(this).parents('.cart_list_td').attr('id');

        $.post(
            '/cart/update',
            {'id':id,'quantity':currentvalue},
            function (result) {
                console.log(result);
                if (result.code == 0){
                    mylayer.okMsg(result.msg);
                    //计算当前的小计
                    var danjia=parseFloat($(that).parents('.good-num').siblings('.good-price').html());
                    var xiaoji=danjia*currentvalue;
                    $(that).parents('.good-num').siblings('.good-total-price').html(xiaoji+'元');

                    //更新总价
                    doPrice();
                }
            },
            'json'
        );
    })

    /*使用 $('#cartTitle').on('click', 'a.add.fl', function () {...}) 为加号按钮绑定点击事件。*/
    $('#cartList').on('click','.add',function () {
        /*获取当前点击元素的兄弟元素中的 <input> 元素，并获取其值，然后将其转换为整数。*/
        var nowvalue=$(this).siblings('input').val();
        nowvalue=parseInt(nowvalue);
        /*增加数量并更新输入框：将当前数量加一，并更新 <input> 的值。*/
        var currentvalue=nowvalue+1;
        $(this).siblings('input').val(currentvalue);
        var that = this;
        var id=$(this).parents('.cart_list_td').attr('id');
        $.post(
            '/cart/update',
            {'id':id,'quantity':currentvalue},
            function (result) {
                console.log(result);
                if (result.code == 0){
                    mylayer.okMsg(result.msg);
                    //计算当前的小计
                    var danjia=parseFloat($(that).parents('.good-num').siblings('.good-price').html());
                    var xiaoji=danjia*currentvalue;
                    $(that).parents('.good-num').siblings('.good-total-price').html(xiaoji+'元');

                    //更新总价
                    doPrice();
                }
            },
            'json'
        );
    })

    //删除按钮
    //事件委托机制
    $('#cartList').on('click', '.del', function (){
        var id = $(this).parents('.list-item').attr('id');
        var that = this;
        layer.confirm(
            '您确认要删除吗?',
            {icon:3},
            function (index){
                $.post(
                    '/cart/deleteById',
                    {'id': id},
                    function (result) {
                        console.log(result);
                        if (result.code == 0) {
                            mylayer.okMsg(result.msg);
                            $(that).parents('.list-item').remove();
                            //更新总价
                            doPrice();
                        }
                    },
                    'json'
                );
            }
        );
    });

    $.post(
        '/cart/list',
        function (result) {
            console.log(result);
            if (result.code == 0) {
                var html = '';
                html+='<ul id="cartTitle" class="cart_list_th clearfix">'
                html+='    <li class="col01">商品名称</li>'
                html+='    <li class="col02">商品单位</li>'
                html+='    <li class="col03">商品价格</li>'
                html+='    <li class="col04">数量</li>'
                html+='    <li class="col05">小计</li>'
                html+='    <li class="col06">操作</li>'
                html+='</ul>'
                var count = 0;
                var totalPrice = 0.0;
                $(result.data).each(function () {
                    count += 1;
                    /*var html = '';*/
                    html+='<ul id="'+this.id+'" class="cart_list_td clearfix">'
                    if (this.checked == 1){
                        html+= '    <li class="col01"><input type="checkbox" class="check ischecked" name="" checked></li>'
                    }else{
                        html+= '    <li class="col01"><input type="checkbox" class="check" name=""></li>'
                    }
                    html+='    <li class="col02"><img src="/pic/'+this.productMainImage+'"></li>'
                    html+='    <li class="col03">'+this.productName+'<br><em>'+this.productSubtitle+'</em></li>'
                    html+='    <li class="col04">500g</li>'
                    html+='    <li class="col05">'+this.productPrice+'</li>'
                    html+='    <li class="col06">'
                    html+='        <div class="num_add">'
                    html+='            <a href="javascript:;" class="add fl">+</a>'
                    html+='            <input type="text" class="num_show fl" value="'+this.quantity+'">'
                    html+='            <a href="javascript:;" class="minus fl">-</a>'
                    html+='        </div>'
                    html+='    </li>'
                    html+='    <li class="col07">'+(this.quantity*this.productPrice)+'元</li>'
                    html+='    <li class="col08"><a href="javascript:;" class="del">删除</a></li>'
                    html+='</ul>'
                    totalPrice += parseFloat(this.quantity*this.productPrice);
                });
                $('#cartTitle').append(html);
                html+='<ul class="settlements">'
                html+='    <li class="col01"><input type="checkbox" id="check-all"  name=""></li>'
                html+='    <li class="col02">全选</li>'
                html+='    <li class="col03">合计(不含运费)：<span>¥</span><em class="goodTotalPrice">'+totalPrice+'</em><br>共计<b>'+count+'</b>件商品</li>'
                html+='    <li class="col04"><a href="/page/order/confirm">去结算</a></li>'
                html+='</ul>'
                $('#totalPrice').append(html);
                $('.countAll').html(count);
                $('#show_count').html(count);
                /*doPrice();*/
                doCheckAll();
            }
        },
        'json'
    );



    function doPrice(){
        //统计所有勾选了的值;
        var items=$('.cart_list_td input[class*="check"]');
        var checkeditems=$('.cart_list_td input[class$="checked"]').parents('.col01').siblings('.goodTotalPrice')
        var totalprice=0;
        for(var i=0;i<checkeditems.length;i++){
            totalprice+=parseFloat(checkeditems[i].innerHTML);
        }
        //改总价
        $('.sumPrice').html(totalprice);
        //改选中数
        $('.selectCount').html(checkeditems.length);
        //改总条数
        $('.allCount').html(items.length);

    }

})